//
//  EmoticonController.swift
//  布局表情键盘
//
//  Created by 孙国强 on 2017/7/6.
//  Copyright © 2017年 孙国强. All rights reserved.
//

import UIKit

private let EmotionCell = "EmotionCell"

class EmoticonController: UIViewController {
    // MARK:- 定义属性
    var emoticonCallBack : (_ emoticon : Emoticon) -> ()

    // MARK:- 懒加载属性
    fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmotionCollectionViewLayout())
    fileprivate lazy var toolBar : UIToolbar = UIToolbar()
    fileprivate lazy var manager = EmoticonManager()
    
    // MARK:- 自定义构造函数
    init(emoticonCallBack : @escaping (_ emoticon : Emoticon) -> ()) {
        
        self.emoticonCallBack = emoticonCallBack
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
//        for package in manager.packages {
//            for emoticon in package.emoticons {
//                print(emoticon.description)
//            }
//        }
    }

}

// MARK:- 设置UI界面内容
extension EmoticonController {
    fileprivate func setupUI() {
        // 添加子控件
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        collectionView.backgroundColor = UIColor.purple
        toolBar.backgroundColor = UIColor.darkGray
        
        // 设置子控件的frame(VFL)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        let views = ["toolBar" : toolBar, "collectionView" : collectionView] as [String : Any]
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-[toolBar]-0-|", options: [.alignAllLeft, .alignAllRight], metrics: nil, views: views)
        view.addConstraints(cons)
        
        // 准备collectionView
        prepareForCollectionView()
        
        // 准备toolBar
        prepareForToolBar()
    }
    
    private func prepareForCollectionView() {
        collectionView.register(EmoticonViewCell.self, forCellWithReuseIdentifier: EmotionCell)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    private func prepareForToolBar() {
        let titles = ["最近", "默认", "emoji", "浪小花"]
        
        var index = 0
        var tempItems = [UIBarButtonItem]()
        for title in titles {
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(EmoticonController.itemClick(item:)))
            item.tag = index
            index += 1
            
            tempItems.append(item)
            tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        tempItems.removeLast()
        toolBar.items = tempItems
        toolBar.tintColor = UIColor.orange
    }
    
    @objc private func itemClick(item : UIBarButtonItem) {
        let tag = item.tag
        
        let indexPath = IndexPath(item: 0, section: tag)
        
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }
}

// MARK:- UICollectionView的数据源和代理方法
extension EmoticonController : UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return manager.packages[section].emoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmotionCell, for: indexPath) as! EmoticonViewCell
        
        cell.backgroundColor = UIColor.purple
        cell.emoticon = manager.packages[indexPath.section].emoticons[indexPath.item]
        
        return cell
    }
    
    /// 代理方法
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // 取出点击的表情
        let package = manager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        
        // 将点击的表情插入最近分组中
        insertRecentlyEmoticon(emoticon: emoticon)
        
        // 将表情回调给外界控制器
        emoticonCallBack(emoticon)
    }
    
    private func insertRecentlyEmoticon(emoticon : Emoticon) {
        // 如果是空白表情或者删除按钮，不需要插入
        if emoticon.isRemove || emoticon.isEmpty {
            return
        }
        
        // 删除一个表情
        if manager.packages.first!.emoticons.contains(emoticon) { // 原来有该表情
            let index = (manager.packages.first!.emoticons.index(of: emoticon))!
            manager.packages.first?.emoticons.remove(at: index)
        } else { // 原来没有这个表情
            manager.packages.first?.emoticons.remove(at: 19)
        }
        
        // 将emoticon插入最近分组中
        manager.packages.first?.emoticons.insert(emoticon, at: 0)
    }
}

class EmotionCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        let itemWH = UIScreen.main.bounds.width / 7
        
        itemSize = CGSize(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        collectionView?.isPagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        let insetMargin = ((collectionView!.bounds.height) - 3 * itemWH) / 2
        collectionView?.contentInset = UIEdgeInsets(top: insetMargin, left: 0, bottom: insetMargin, right: 0)
    }
}

